import { Injectable, BadRequestException } from '@nestjs/common';
import { RedisService } from '../redis/redis.service';

@Injectable()
export class VerificationService {
  private readonly CODE_EXPIRE_TIME = 300; // 验证码有效期5分钟
  private readonly CODE_SEND_INTERVAL = 60; // 发送间隔1分钟
  private readonly CODE_KEY_PREFIX = 'resume:verification:';
  private readonly CODE_SEND_TIME_PREFIX = 'resume:verification:send:';

  constructor(private readonly redisService: RedisService) {}

  /**
   * 生成并存储验证码
   * @param email 邮箱地址
   * @returns 生成的验证码
   */
  async generateAndStoreCode(email: string): Promise<string> {
    // 检查发送间隔
    const lastSendTime = await this.redisService.get<number>(`${this.CODE_SEND_TIME_PREFIX}${email}`);
    if (lastSendTime) {
      const timePassed = Math.floor((Date.now() - lastSendTime) / 1000);
      if (timePassed < this.CODE_SEND_INTERVAL) {
        throw new BadRequestException(`请等待 ${this.CODE_SEND_INTERVAL - timePassed} 秒后再次发送验证码`);
      }
    }

    // 生成6位随机验证码
    const code = Math.random().toString().slice(2, 8);
    
    // 存储验证码和发送时间
    await Promise.all([
      this.redisService.set(`${this.CODE_KEY_PREFIX}${email}`, code, this.CODE_EXPIRE_TIME),
      this.redisService.set(`${this.CODE_SEND_TIME_PREFIX}${email}`, Date.now(), this.CODE_SEND_INTERVAL)
    ]);

    return code;
  }

  /**
   * 验证验证码
   * @param email 邮箱地址
   * @param code 验证码
   * @returns 验证是否成功
   */
  async verifyCode(email: string, code: string): Promise<boolean> {
    const storedCode = await this.redisService.get<string>(`${this.CODE_KEY_PREFIX}${email}`);
    console.log(storedCode);
    if (!storedCode) {
      throw new BadRequestException('验证码已过期或不存在');
    }

    if (storedCode !== code) {
      throw new BadRequestException('验证码错误');
    }

    // 验证成功后删除验证码
    await this.redisService.del(`${this.CODE_KEY_PREFIX}${email}`);
    return true;
  }

  /**
   * 清除验证码
   * @param email 邮箱地址
   */
  async clearCode(email: string): Promise<void> {
    await Promise.all([
      this.redisService.del(`${this.CODE_KEY_PREFIX}${email}`),
      this.redisService.del(`${this.CODE_SEND_TIME_PREFIX}${email}`)
    ]);
  }
} 